const router = require('koa-router')();

router.prefix('/api')

// 写你自己的路由
// 注册接口
router.post('/registry', async ctx => {
    const {
        password,
        phone
    } = ctx.request.body;

    console.log(password,'pwd',phone,'phone');
    const res = await ctx.searchQuery(`select phone from user WHERE phone='${phone}'`)
    // 判断是否存在该数据
    if (res.length) {
        ctx.body = {
            code: "SUCCESS",
            msg: "该手机号已注册",
            status: 200
        }

        return;
    } else {
        const addres = await ctx.searchQuery(`INSERT INTO user (phone,password) VALUES ('${phone}','${password}');`);

        ctx.body = {
            code: "SUCCESS",
            msg: "注册成功",
            status: 200
        }
    }
})

// 登录接口
router.post('/login', async ctx => {
    const {
        phone,
        password
    } = ctx.request.body;
    console.log(phone,'phone',password,'password');

    const res = await ctx.searchQuery(`select * from user WHERE phone='${phone}' AND password='${password}';`)

    if (res.length) {
        ctx.body = {
            code: "SUCCESS",
            msg: "登录成功",
            status: 200
        }
        return;
    }

    ctx.body = {
        code: "FAIL",
        msg: "用户名或密码输入有误",
        status: 200
    }
})

// 数据添加接口
router.post('/addCourse', async ctx => {
    // 获取参数
    const {
        name,
        jineng,
        lilun,
        date
    } = ctx.request.body;

    const res = await ctx.searchQuery(`INSERT INTO curList (name,jineng,lilun,date) VALUES ('${name}','${jineng}','${lilun}','${date}')`);

    if (res.insertId) {
        ctx.body = {
            code: "SUCESS",
            msg: "添加成功",
            status: 200,
            data: {
                id: res.insertId
            }
        }
    }
})

// 查询接口
router.get("/searchCurList", async ctx => {
    const {
        id,
        pageNum,
        pageSize
    } = ctx.query;

    if (id) {
        const res = await ctx.searchQuery(`select * from curList WHERE id=${id*1};`);
        if (res.length) {
            ctx.body = {
                code: "SUCCESS",
                msg: "数据查询成功",
                status: 200,
                data: res
            }
        } else {
            ctx.body = {
                code: "SUCCESS",
                msg: "没有该数据",
                status: 200,
                data: null
            }
        }
        return;
    }

    // 查询列表
    const res = await ctx.searchQuery(`SELECT * FROM curList LIMIT ${pageSize*1} OFFSET ${(pageNum-1)*pageSize}`)
    ctx.body = {
        code: "SUCCESS",
        msg: "数据查询成功",
        status: 200,
        data: res
    }
})

module.exports = router;